import store from '@/store/store.js'
import address from './address.js'
import Vue from 'vue'

const request = ({url, contentType = 'application/json;charset=UTF-8', method, data}) => {
   let token = ''
   if(url.indexOf('login') == -1) {
      token = store.getters.token
   }
   return new Promise((resolve, reject) => {
      uni.request({
         url: address.baseURL + url,
         header: {
           'content-type': contentType,
           token
         },
         method,
         data,
         success(res) {
            if(url.indexOf('login') == -1) res.data ? resolve(res.data) : resolve(res)
            resolve(res)
         },
         fail(err) {
            reject(err)
         }
      })
   })
}
const vue = new Vue()
let loading = false
let argsObj = ''
const skipAnimationURL = ['/forum/likes', '/forum/views']
uni.addInterceptor('request', {
   invoke: (args) => {
      if(!loading && isSkiploadingAnimation(args)) {
         // 350ms后触发加载动画 ==> 页面切换晚于网络请求 页面切换时间为300ms
         setTimeout(() => {
            uni.$emit('showLoading')
            argsObj = args
            loading = true
         }, 250)
      }
	   if(args.url != 'https://api.map.baidu.com/api_region_search/v1/' && args.url.indexOf('login') == -1) {
         if(args.header) args.header.OS = 'app'
         if(args.header) args.header.name = store.getters.username
		   if(store.getters.token && args.header) args.header.token = store.getters.token
	   }
      return args
   },
   success: (res) => {
      // console.log('request：success', res);
      const { statusCode } = res
      uni.hideLoading()
      randomLoadingAnimation()
      if(statusCode === 404) {
         toastTip('资源丢失')
      }
      if(res.data.code === 200 && statusCode === 200) return res
      if(res.data.code === 500 || statusCode === 500) toastTip('服务器错误')
      if(statusCode === 403) {
         uni.showToast({
            title: '身份过期',
            icon: 'none'
         })
         uni.reLaunch({
            url: '/pages/login'
         })
      }
   },
   fail: (err) => {
      console.log('request：err', err);
      if(err.errMsg.indexOf('timeout') != -1 || err.errMsg.indexOf('ETIMEDOUT') != -1) {
         toastTip('请求超时')
      }else {
         toastTip('请求失败')
      }
      uni.hideLoading()
      randomLoadingAnimation()
      return false
   }
})

const toastTip = (msg) => {
   uni.showToast({
      icon: 'none',
      title: msg,
      position: 'bottom',
      duration: 2 * 1000
   })
}

const isSkiploadingAnimation = (args) => {
   return skipAnimationURL.findIndex(url => {
      return args.url.indexOf(url) !== -1
   }) === -1
}

const randomLoadingAnimation = () => {
   // 1s ~ 3s
   // let duration = Math.floor(Math.random() * 3000 + 1000)
   let duration = 500
   setTimeout(() => {
      uni.$emit('hideLoading')
      loading = false
   }, duration)
}

export default request